<template>
  <q-input v-model:model-value="inputValue" :class="{ hoverClearInput: !!inputValue }" v-bind="$attrs" @blur="onBlur">
    <template #append>
      <slot name="append" />
    </template>
    <q-menu v-if="list && list.length" v-model="isShow" max-height="42vh" no-focus fit>
      <q-list style="min-width: 100px">
        <q-item v-for="(item, i) in list.filter(d => typeof d !== 'undefined')" :key="item[valueAttr] || item" v-close-popup :tabindex="i" clickable @click="doSelect(item)">
          <q-item-section v-if="typeof item === 'object'">
            <q-item-label>{{ item[valueAttr] }}</q-item-label>
            <q-item-label v-if="tipAttr in item" caption>item[tipAttr]</q-item-label>
          </q-item-section>
          <q-item-section v-else>{{ item }}</q-item-section>
        </q-item>
      </q-list>
    </q-menu>
  </q-input>
</template>

<script setup>
const props = defineProps({
  modelValue: {
    type: [ String, Number ],
  },
  list: {
    type: Array,
    default() {
      return []
    },
  },
  valueAttr: {
    type: String,
    default: 'value',
  },
  labelAttr: {
    type: String,
    default: 'label',
  },
  tipAttr: {
    type: String,
    default: 'tip',
  },
})

const $emit = defineEmits([ 'update:modelValue' ])

defineOptions({
  name: 'InputWithSuggestion',
})

const isShow = ref(false)
const isFromSelect = ref(false)
const showTimer = ref(null)

const inputValue = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    $emit('update:modelValue', val)
  },
})

function doSelect(item) {
  isFromSelect.value = true
  inputValue.value = item[props.valueAttr] || item
}

function onFocus() {
  setTimeout(() => {
    if (isFromSelect.value) {
      return (isFromSelect.value = false)
    }
    isShow.value = true
  }, 300)
}

function onBlur() {
  setTimeout(() => {
    if (isFromSelect.value) {
      return
    }
    if (showTimer.value) {
      clearTimeout(showTimer.value)
    }
    isShow.value = false
    isFromSelect.value = false
  }, 300)
}
</script>
